package com.arcanite.dailyplanner.view.fragment;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.arcanite.dailyplanner.R;
import com.arcanite.dailyplanner.view.adapter.ContentPageAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * Created by Arcanite on 2016/10/19.
 */

public class HomeFragment extends Fragment{
    private View view = null;
    private static HomeFragment sHomeFragment = null;

    private List<ContentFragment> mListFragment;
    private List<String> mListTitle;

    public static HomeFragment newInstance(){
        if (sHomeFragment == null){
            sHomeFragment = new HomeFragment();
            sHomeFragment.mListFragment = new ArrayList<>();
            sHomeFragment.mListTitle = new ArrayList<>();
        }
        return sHomeFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 进行判断以避免每次都要加载，减少资源消耗
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_home, container, false);
            initView(view);
        }
        return view;
    }

    /**
     * 应该把标题和内容fragment的初始化剥离出来，而不是在这个fragment里进行设置
     * @param view view
     */
    private void initView(View view) {
        TabLayout tabTitle = (TabLayout) view.findViewById(R.id.tab_title);
        ViewPager vpContent = (ViewPager) view.findViewById(R.id.vp_content);

        // 添加tab
        for (int i = 0; i < mListTitle.size(); i++){
            tabTitle.addTab(tabTitle.newTab().setText(mListTitle.get(i)));
        }

        ContentPageAdapter mAdapter = new ContentPageAdapter(getActivity().getSupportFragmentManager(), mListFragment);
        vpContent.setAdapter(mAdapter);
        tabTitle.setupWithViewPager(vpContent);

        // 需要在setup之后为TabLayout设置标题，newTab()时那样设置无法设置成功的原因未知
        for (int i = 0; i < mListTitle.size(); i++) {
            TabLayout.Tab tab = tabTitle.getTabAt(i);
            if (tab != null) {
                tab.setText(mListTitle.get(i));
            }
        }
    }

    public void addPage(String title, ContentFragment fragment){
        mListTitle.add(title);
        mListFragment.add(fragment);
    }

}
